package com.example.blogsystem.config;

import com.example.blogsystem.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseHandle implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    private Result<Object> result = new Result<>();
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //所有接口都进行统一结果返回
        return true;
        /*
        可以手动指定哪些接口不用统一结果。
         */
    }

    @Override
    @SneakyThrows // 会自动生成try catch
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 统一返回结果逻辑
        // 判断body是否是Result类型
        if(body instanceof Result) {
            return body;
        }
        if(body instanceof String) {
            // 对String类型单独处理，因为String类型会造成类型转换失败
            // 转换成json格式的字符串
            return objectMapper.writeValueAsString(result.success(body));
        }
        return result.success(body); // body 表示返回的数据
    }
}
